#include "writeVertexBuffer.hpp"
#include "Log.hpp"
#include <algorithm>
using namespace std;
using namespace m3g;

/**
*
*/
unsigned int writeVertexBuffer (M3GWriter* writer, MQObject mq_obj, 
	unsigned int positions_index , float positions_scale , float* positions_bias , 
	unsigned int normals_index   , float normals_scale   , float* normals_bias   ,
	unsigned int colors_index    , float colors_scale    , float* colors_bias    ,
	unsigned int tex_coords_index, float tex_coords_scale, float* tex_coords_bias)
{
	Log:: print ("Write VertexBuffer.\n");

	M3GObject3DStruct     obj;
	M3GVertexBufferStruct vbuf;
	vbuf.positions_index       = positions_index;
	vbuf.position_scale        = positions_scale;
	vbuf.position_bias[0]      = positions_bias[0];
	vbuf.position_bias[1]      = positions_bias[0];
	vbuf.position_bias[2]      = positions_bias[0];
	vbuf.normals_index         = normals_index;
	vbuf.colors_index          = colors_index;
	vbuf.texcoord_array_count  = (tex_coords_index != 0) ? 1 : 0;
    if (vbuf.texcoord_array_count > 0) {
    	vbuf.texcoords_index       = new unsigned int[1];
    	vbuf.texcoords_index[0]    = tex_coords_index;
    	vbuf.texcoord_scale        = new float[1];
    	vbuf.texcoord_scale[0]     = tex_coords_scale;
    	vbuf.texcoord_bias         = new float*[1];
    	vbuf.texcoord_bias[0]      = new float[3];
    	vbuf.texcoord_bias[0][0]   = tex_coords_bias[0];
    	vbuf.texcoord_bias[0][1]   = tex_coords_bias[1];
    	vbuf.texcoord_bias[0][2]   = tex_coords_bias[2];
    }

	unsigned int object_index;

	writer->startObject       (M3G_TYPE_VERTEX_BUFFER, &object_index);
	writer->writeObject3D     (obj);
	writer->writeVertexBuffer (vbuf);
	writer->endObject         ();

	return object_index;
}